package leetcode.editor.cn;

import java.util.PriorityQueue;

/**
 * @author: yangwk
 * @date: 2023/2/21
 * @description:
 **/
public class P1326 {
    public static void main(String[] args) {
        System.out.println(minTaps(9, new int[]{0, 5, 0, 3, 3, 3, 1, 4, 0, 4}));
    }

    public static int minTaps(int n, int[] ranges) {
        int length = ranges.length;
        PriorityQueue<int[]> queue = new PriorityQueue<>((o1, o2) -> {
            int i1 = o1[1] - o1[0];
            int i2 = o2[1] - o2[0];
            if (i1 != i2) {
                return i2 - i1;
            }
            if (o1[1] != o2[1]) {
                return o2[1] - o1[1];
            }
            return o2[0] - o1[0];
        });
        for (int i = 0; i < length; i++) {
            int range = ranges[i];
            int[] arr = new int[2];
            arr[0] = i - range < 0 ? 0 : i - range;
            arr[1] = i + range > n ? n : i + range;
            queue.add(arr);
        }
        int count = 1;
        while (!queue.isEmpty()) {
            int[] poll1 = queue.poll();
            if (poll1[0] <= 0 && poll1[1] >= n) {
                return count;
            }
            int[] poll2 = queue.poll();
            int left1 = poll1[0];
            int right1 = poll1[1];
            int left2 = poll2[0];
            int right2 = poll2[1];
            if (left1 > right2 || left2 > right1) {
                return -1;
            } else {
                int minLeft = Math.min(left1, left2);
                int minRight = Math.max(right1, right2);
                if (minLeft == left1 && minRight == right1) {
                    queue.add(poll1);
                } else {
                    count++;
                    queue.add(new int[]{minLeft, minRight});
                }
            }
        }
        return -1;
    }
}
